package com.search;

import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zghgchao 2017/12/30 15:03
 */
public class SearchServlet extends HttpServlet {
    static List<String> datas = new ArrayList<String>();

    static {
        //模拟数据
        datas.add("ajax");
        datas.add("ajax post");
        datas.add("ajax get");
        datas.add("bill");
        datas.add("becky");
        datas.add("james");
        datas.add("jerry");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        System.out.println("-------------请求服务器-------------");
        //首先获得客户端发送来的数据keyword
        String keyword = req.getParameter("keyword");
        //获得关键字之后进行处理，得到关联数据
        List<String> listData = getData(keyword);
        //返回JSON格式
        System.out.println(JSONArray.fromObject(listData));
        JSONArray jsonArray = JSONArray.fromObject(listData);
        resp.getWriter().write(jsonArray.toString());
    }

    //获得关联数据的方法
    public List<String> getData(String keyword) {
        List<String> list = new ArrayList<String>();

        for (String data : datas) {
            if (data.contains(keyword)) {//如果数据库datas中包含keyword，则将包含关键字的数据放在List上返回
                list.add(data);
            }
        }
        return list;
    }
}
